<?php
/**
 * Created by PhpStorm.
 * User: geyouwen
 * Date: 16/7/13
 * Time: 下午5:26
 */
//让array_column()函数兼容低版本
function i_array_column($input, $columnKey, $indexKey=null){
    if(!function_exists('array_column')){
        $columnKeyIsNumber  = (is_numeric($columnKey))?true:false;
        $indexKeyIsNull            = (is_null($indexKey))?true :false;
        $indexKeyIsNumber     = (is_numeric($indexKey))?true:false;
        $result                         = array();
        foreach((array)$input as $key=>$row){
            if($columnKeyIsNumber){
                $tmp= array_slice($row, $columnKey, 1);
                $tmp= (is_array($tmp) && !empty($tmp))?current($tmp):null;
            }else{
                $tmp= isset($row[$columnKey])?$row[$columnKey]:null;
            }
            if(!$indexKeyIsNull){
                if($indexKeyIsNumber){
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key))?current($key):null;
                    $key = is_null($key)?0:$key;
                }else{
                    $key = isset($row[$indexKey])?$row[$indexKey]:0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    }else{
        return array_column($input, $columnKey, $indexKey);
    }
}

//change array index
function changeArrIndex($arr, $index)
{
    if(!$arr) return $arr;
    $tmp = array();
    foreach($arr as $key => $val)
    {
        $tmp[$val[$index]] = $val;
    }
    return $tmp;
}

function deleteAll($path) {
    $op = dir($path);
    while(false != ($item = $op->read())) {
        if($item == '.' || $item == '..') {
            continue;
        }
        if(is_dir($op->path.'/'.$item)) {
            deleteAll($op->path.'/'.$item);
            rmdir($op->path.'/'.$item);
        } else {
            unlink($op->path.'/'.$item);
        }
    }
}


//qiniuOss
/**
 * @param $file $_FILES['file']
 * @param string $bucket
 * @param string $uri
 */
function qiniuOss($file, $bucket='app' , $uri = 'http://lumen.dev.com/qiniu/upload')
{
    // 参数数组
    $fp = fopen($file['tmp_name'],'rb');
    $file = fread($fp, $file["size"]);
    $data = array (
        'oss_method' => 'binary',
        'oss_bucket' => $bucket,
        'file' => base64_encode($file)
    );
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $uri );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
    $return = curl_exec ( $ch );
    curl_close ( $ch );
    return $return;
}

// aliyun oss
/**
 * @param $file $_FILES['file']
 * @param string $bucket
 * @param string $uri
 */
function aliyunoss($file , $bucket='aliyunappbucket', $uri = 'http://lumen.dev.com/aliyun/upload')
{
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $uri );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ($ch,  CURLOPT_HTTPHEADER, array('Expect:'));
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );

    if(version_compare(PHP_VERSION, '5.5') >= 0)
    {
        $upload_file = new CURLFile($file['tmp_name'], $file['type'] ,$file['name']);
        $data = array (
            'oss_bucket' => $bucket,
            'file' => $upload_file,
        );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
    } else {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        curl_filefields($ch, array('oss_bucket' => $bucket, 'ext' => $ext), $file);
    }
    $return = curl_exec ( $ch );
    curl_close ( $ch );
    return $return;
}


/**
 * For safe multipart POST request for PHP5.3 ~ PHP 5.4.
 * @param $ch
 * @param array $assoc
 * @param array $files
 * @return bool
 */
function curl_filefields($ch,  $assoc=array(),  $files = array())
{
    // invalid characters for "name" and "filename"
    static $disallow = array("\0", "\"", "\r", "\n");

    // build normal parameters
    foreach ($assoc as $k => $v) {
        $k = str_replace($disallow, "_", $k);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"",
            "",
            filter_var($v),
        ));
    }

    // build file parameters
    foreach ($files as $k => $v) {
        switch (true) {
            case false === $v = realpath(filter_var($v)):
            case !is_file($v):
            case !is_readable($v):
                continue; // or return false, throw new InvalidArgumentException
        }
        $data = file_get_contents($v);
        $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
        $k = str_replace($disallow, "_", $k);
        $v = str_replace($disallow, "_", $v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
            "Content-Type: application/octet-stream",
            "",
            $data,
        ));
    }

    // generate safe boundary
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));

    // add boundary for each parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });

    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";
    // set options

    return @curl_setopt_array($ch, array(
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body),
        CURLOPT_HTTPHEADER => array(
            "Expect:",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
        ),
    ));
}

